<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


















  
  
    
  
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.css">







<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=7.1.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=7.1.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="最近从图书馆借了本介绍SQL的书，打算复习一下基本语法，记录一下笔记，整理一下思路，以备日后复习之用。 PS：本文适用SQL Server2008语法。">
<meta name="keywords" content="数据库,SQL">
<meta property="og:type" content="article">
<meta property="og:title" content="SQL基础语法笔记教程整理">
<meta property="og:url" content="https://michael728.github.io/2016/05/03/SQL/index.html">
<meta property="og:site_name" content="Michael翔">
<meta property="og:description" content="最近从图书馆借了本介绍SQL的书，打算复习一下基本语法，记录一下笔记，整理一下思路，以备日后复习之用。 PS：本文适用SQL Server2008语法。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://ww4.sinaimg.cn/large/6d9475f6jw1f2tqc5pnivj207902bjrg.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/6d9475f6jw1f2tqcumt9fj206c02jdfy.jpg">
<meta property="og:image" content="http://ww4.sinaimg.cn/large/6d9475f6jw1f2tydodr55j20jc0eq43d.jpg">
<meta property="og:updated_time" content="2020-01-05T15:47:56.116Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SQL基础语法笔记教程整理">
<meta name="twitter:description" content="最近从图书馆借了本介绍SQL的书，打算复习一下基本语法，记录一下笔记，整理一下思路，以备日后复习之用。 PS：本文适用SQL Server2008语法。">
<meta name="twitter:image" content="http://ww4.sinaimg.cn/large/6d9475f6jw1f2tqc5pnivj207902bjrg.jpg">



  <link rel="alternate" href="/atom.xml" title="Michael翔" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://michael728.github.io/2016/05/03/SQL/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>SQL基础语法笔记教程整理 | Michael翔</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?1c9958c951d5a7661571422e0340e156";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <meta name="referrer" content="never">
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Michael翔</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">因上努力，果上随缘！</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tools">

    
    
    
      
    

    

    <a href="/tools/" rel="section"><i class="menu-item-icon fa fa-fw fa-location-arrow"></i> <br>利器</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-books">

    
    
    
      
    

    

    <a href="/books" rel="section"><i class="menu-item-icon fa fa-fw fa-book"></i> <br>阅读</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-movies">

    
    
    
      
    

    

    <a href="/movies" rel="section"><i class="menu-item-icon fa fa-fw fa-film"></i> <br>观影</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-think">

    
    
    
      
    

    

    <a href="/think" rel="section"><i class="menu-item-icon fa fa-fw fa-lightbulb-o"></i> <br>一言</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    
  
  

  

  <a href="https://github.com/michael728" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://michael728.github.io/2016/05/03/SQL/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Michael翔">
      <meta itemprop="description" content="DevOps CICD Blog 持续学习">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Michael翔">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">SQL基础语法笔记教程整理

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2016-05-03 16:55:41" itemprop="dateCreated datePublished" datetime="2016-05-03T16:55:41+00:00">2016-05-03</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2020-01-05 15:47:56" itemprop="dateModified" datetime="2020-01-05T15:47:56+00:00">2020-01-05</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/数据库/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>最近从图书馆借了本介绍SQL的书，打算复习一下基本语法，记录一下笔记，整理一下思路，以备日后复习之用。</p>
<p>PS：本文适用SQL Server2008语法。</p>
<a id="more"></a>
<h1 id="一、关系型数据库和SQL"><a href="#一、关系型数据库和SQL" class="headerlink" title="一、关系型数据库和SQL"></a>一、关系型数据库和SQL</h1><p>实际上准确的讲，SQL是一门语言，而不是一个数据库。</p>
<p>什么是SQL呢？简而言之，SQL就是维护和使用关系型数据库中的的数据的一种标准的计算机语言。</p>
<h2 id="1-1-SQL语言主要有3个主要的组成部分。"><a href="#1-1-SQL语言主要有3个主要的组成部分。" class="headerlink" title="1.1 SQL语言主要有3个主要的组成部分。"></a>1.1 SQL语言主要有3个主要的组成部分。</h2><ol>
<li>DML(Data Manipulation Language)数据操纵语言。这个模块可以让我们检索、修改、增加、删除数据库中的数据。</li>
<li>DDL(Data Definition Language)数据定义语言。是的我们能够创建和修改数据库本身。如：DDL提供<code>ALTER</code>语句，他让我们可以修改数据库中表的设计。</li>
<li>DCL(Data Control Language)数据控制语言，用于维护数据库的安全。</li>
</ol>
<p>在SQL术语中，记录(record)和字段(field)实际上就称为行(row)和列(column)。  </p>
<h2 id="1-2-主键和外键"><a href="#1-2-主键和外键" class="headerlink" title="1.2 主键和外键"></a>1.2 主键和外键</h2><p>主键之所以有必要：</p>
<ul>
<li>首先使你唯一标识表中单独的一行。主键确保了唯一性。</li>
<li>可以很容易的将一个表和另一个表关联。</li>
<li>主键一般就会自动默认创建索引，提高了查询速度。</li>
</ul>
<p>外键就是说A表中的某个字段，同时是B中的主键，那么这个字段就是A表中的外键。希望A表中的这个外键的值必须是B中已经存在的值。</p>
<h2 id="1-3-数据类型"><a href="#1-3-数据类型" class="headerlink" title="1.3 数据类型"></a>1.3 数据类型</h2><p>一般来讲，有3中重要的数据类型：</p>
<ol>
<li>数字(Numeric)   </li>
<li>字符(Character)  </li>
<li>以及日期/时间(Date/Time)</li>
</ol>
<p><code>bit</code>是数字型，它只允许两个值，0和1。</p>
<p>字符类型区别[^1]：<br>[^1]:<a href="http://www.cnblogs.com/yelaiju/archive/2010/05/29/1746826.html" target="_blank" rel="noopener">varchar和Nvarchar区别</a></p>
<table>
<thead>
<tr>
<th>类型</th>
<th>长度</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>char</code></td>
<td>固定长度</td>
</tr>
<tr>
<td><code>nchar</code></td>
<td>固定长度</td>
<td>处理unicode数据类型(所有的字符使用两个字节表示)</td>
</tr>
<tr>
<td><code>varchar</code></td>
<td>可变长度</td>
<td>效率没char高 灵活</td>
</tr>
<tr>
<td><code>nvarchar</code></td>
<td>可变长度</td>
<td>处理unicode数据类型(所有的字符使用两个字节表示)</td>
</tr>
</tbody>
</table>
<ul>
<li>1字节=8位</li>
<li>bit就是位，也叫比特位，是计算机表示数据最小的单位。</li>
<li>byte就是字节，1byte=8bit，1byte就是1B；</li>
<li>一个字符=2字节；</li>
</ul>
<h2 id="1-3-空值"><a href="#1-3-空值" class="headerlink" title="1.3 空值"></a>1.3 空值</h2><p>空值不等于空格或空白。使用NULL表示空值。</p>
<h1 id="二、简单增删改查"><a href="#二、简单增删改查" class="headerlink" title="二、简单增删改查"></a>二、简单增删改查</h1><h2 id="2-1-查（列名有空格的情况）"><a href="#2-1-查（列名有空格的情况）" class="headerlink" title="2.1 查（列名有空格的情况）"></a>2.1 查（列名有空格的情况）</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT [ last name]</span><br><span class="line">FROM Customers</span><br></pre></td></tr></table></figure>
<p>用方括号将有空格的列名括起来。<br>PS: MySql中用重音符<strong>`</strong>（~）按键。Oracle用双引号。</p>
<h3 id="查询顺序-SQL执行顺序-2："><a href="#查询顺序-SQL执行顺序-2：" class="headerlink" title="查询顺序,SQL执行顺序^2："></a>查询顺序,SQL执行顺序<a href="[SQL总结（一）基本查询](http://www.imooc.com/article/1412)">^2</a>：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Select -1&gt;选择列,-2&gt;distinct,-3&gt;top</span><br><span class="line">  1&gt;…From 表</span><br><span class="line">  2&gt;…Where 条件</span><br><span class="line">  3&gt;…Group by 列</span><br><span class="line">  4&gt;…Having 筛选条件</span><br><span class="line">  6&gt;…Order by 列</span><br></pre></td></tr></table></figure>
<h2 id="2-2-增"><a href="#2-2-增" class="headerlink" title="2.2 增"></a>2.2 增</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">INSERT INTO tablename</span><br><span class="line">(columnlist)</span><br><span class="line">VALUES</span><br><span class="line">(RowValues1)</span><br><span class="line">(RowValues2)</span><br><span class="line">(repeat any number of times)</span><br></pre></td></tr></table></figure>
<h2 id="2-3-改"><a href="#2-3-改" class="headerlink" title="2.3 改"></a>2.3 改</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">UPDATE  table</span><br><span class="line">SET column1=expression1,column2=expression2(repeat any number of times)</span><br><span class="line">WHERE condition</span><br></pre></td></tr></table></figure>
<h2 id="2-4-删"><a href="#2-4-删" class="headerlink" title="2.4 删"></a>2.4 删</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">DELETE</span><br><span class="line">FROM table</span><br><span class="line">WHERE condition</span><br></pre></td></tr></table></figure>
<p>删除前可以验证一下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">COUNT（*）</span><br><span class="line">FROM table</span><br><span class="line">WHERE condition</span><br></pre></td></tr></table></figure></p>
<p>如果想要删除所有的行，可以：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DELETE FROM table</span><br></pre></td></tr></table></figure></p>
<p>或者<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">TRUNCATE TABLE table</span><br></pre></td></tr></table></figure></p>
<p><code>TRUNCATE TABLE</code>优势在于速度更快，但是不提供记录事务的结果。<br>另外一个不同点是，<code>TRUNCATE TABLE</code>重新设置了用于自增型的列的当前值，<code>DELETE</code>不会。</p>
<h1 id="三、别名"><a href="#三、别名" class="headerlink" title="三、别名"></a>三、别名</h1><p>关键字：AS</p>
<h2 id="3-1-计算字段"><a href="#3-1-计算字段" class="headerlink" title="3.1 计算字段"></a>3.1 计算字段</h2><p>使用计算字段可以做如下的事情：</p>
<ul>
<li>选择特定的单词或者数值</li>
<li>对单个或者多个列进行计算</li>
<li>把列和直接量组合在一起。</li>
</ul>
<h2 id="3-2-直接量"><a href="#3-2-直接量" class="headerlink" title="3.2 直接量"></a>3.2 直接量</h2><p>这个直接量和表中的数据没有任何关系，就是为了说明所用，下面这种类型的表达式就叫做直接量(literal value)。<br><img src="http://ww4.sinaimg.cn/large/6d9475f6jw1f2tqc5pnivj207902bjrg.jpg" alt></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT &apos;直接量&apos; AS `类型`,firstname,lastname </span><br><span class="line">FROM `customers` ;</span><br></pre></td></tr></table></figure>
<p><img src="http://ww1.sinaimg.cn/large/6d9475f6jw1f2tqcumt9fj206c02jdfy.jpg" alt><br>如图，结果中直接量就在一列中了。</p>
<h2 id="3-3-算数运算"><a href="#3-3-算数运算" class="headerlink" title="3.3 算数运算"></a>3.3 算数运算</h2><p>例子1：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT  num*price AS total</span><br><span class="line">FROM orders</span><br></pre></td></tr></table></figure></p>
<p>例子2：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT  firstname+&apos; &apos;+lastname AS &apos;fullname&apos;</span><br><span class="line">FROM users</span><br></pre></td></tr></table></figure></p>
<p>在MySql中连接要是用<code>CONCAT</code>函数：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT OrderID,FirstName,LastName,</span><br><span class="line">CONCAT(FirstName,&apos; &apos;,LastName) AS &apos;fullname&apos;</span><br><span class="line">FROM orders</span><br></pre></td></tr></table></figure></p>
<h2 id="3-4-别名"><a href="#3-4-别名" class="headerlink" title="3.4 别名"></a>3.4 别名</h2><p>1）列的别名<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT firstname AS fn</span><br><span class="line">FROM customers</span><br></pre></td></tr></table></figure></p>
<p>2） 表的别名<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT firstname </span><br><span class="line">FROM customers AS cu</span><br></pre></td></tr></table></figure></p>
<p>说明：</p>
<ol>
<li>列的别名是为了显示用的，别名会作为查询结果的表头，不能在WHERE中使用列的别名，会出错！！！</li>
<li>表的别名确实是为了方便操作用的，可以在WHERE中使用列的别名进行！</li>
</ol>
<h1 id="四、使用函数"><a href="#四、使用函数" class="headerlink" title="四、使用函数"></a>四、使用函数</h1><p>函数要有一组圆括号跟在关键字后边，圆括号告诉我们，这是一个函数！</p>
<h2 id="4-1-字符函数"><a href="#4-1-字符函数" class="headerlink" title="4.1 字符函数"></a>4.1 字符函数</h2><h3 id="LEFT-amp-RIGHT"><a href="#LEFT-amp-RIGHT" class="headerlink" title="LEFT&amp;RIGHT"></a>LEFT&amp;RIGHT</h3><p> <code>LEFT(CharacterValue,NumberOfCharacters)</code><br>含义：选择<code>CharacterValue</code>字段的左边<code>NumberOfCharacters</code>几个字符。<br>ps:RIGHT是右边几个字符。</p>
<h3 id="LTRIM-amp-RTRIM"><a href="#LTRIM-amp-RTRIM" class="headerlink" title="LTRIM&amp;RTRIM"></a>LTRIM&amp;RTRIM</h3><p> <code>LTRIM(CharacterValue)</code><br> 可以删除左边开始的空格。RTRIM作用类似。</p>
<h3 id="SUBSTRING"><a href="#SUBSTRING" class="headerlink" title="SUBSTRING"></a>SUBSTRING</h3><p><code>SUBSTRING(CharacterValue,StartPositon,NumberOfCharacters)</code><br>含义：选择从开始位置（包括），N个长度的字符。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">SUBSTRING(&apos;thewhitegoat&apos;,4,5) AS &apos;The Answer&apos;</span><br></pre></td></tr></table></figure></p>
<p>返回：white</p>
<h2 id="4-2-日期-时间函数"><a href="#4-2-日期-时间函数" class="headerlink" title="4.2 日期/时间函数"></a>4.2 日期/时间函数</h2><h3 id="GETDATE"><a href="#GETDATE" class="headerlink" title="GETDATE"></a>GETDATE</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT GETDATE()</span><br></pre></td></tr></table></figure>
<p>返回当前日期和时间。<br>PS：在MySql中，等价函数是<code>NOW</code>，在Oracle中是<code>CURRENT_DATE</code>。</p>
<h3 id="DATEPART"><a href="#DATEPART" class="headerlink" title="DATEPART"></a>DATEPART</h3><p>能够分析具体的日期，并且返回诸如该日期是该月中的第几天，或者该年份中的第几周等信息。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DATEPART(datepart,DateValue)</span><br></pre></td></tr></table></figure></p>
<p>datepart可以是许多不同的值，如下都是有效值：</p>
<ul>
<li>year</li>
<li>quarter</li>
<li>month</li>
<li>dayofyear</li>
<li>day</li>
<li>week</li>
<li>weekday</li>
<li>hour</li>
<li>minute</li>
<li>second</li>
</ul>
<h3 id="DATEDIFF"><a href="#DATEDIFF" class="headerlink" title="DATEDIFF"></a>DATEDIFF</h3><p>可以让我们得到任意两个日期之间相差的天数（或周数、月数等）。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DATEDIFF(datepart1,startdate1,startdate2)</span><br></pre></td></tr></table></figure></p>
<table>
<thead>
<tr>
<th>DATEDIFF Function Expression</th>
<th>Resulting Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>DATEDIFF(day,’7/8/2009’,’8/14/2009’)</td>
<td>37</td>
</tr>
<tr>
<td>DATEDIFF(week,’7/8/2009’,’8/14/2009’)</td>
<td>5</td>
</tr>
<tr>
<td>DATEDIFF(month,’7/8/2009’,’8/14/2009’)</td>
<td>1</td>
</tr>
<tr>
<td>DATEDIFF(year,’7/8/2009’,’8/14/2009’)</td>
<td>0</td>
</tr>
</tbody>
</table>
<p>PS:MySql中，DATEDIFF函数只允许我们计算两个日期之间的天数，如果想要得到一个正数，结束的日期通常要作为第一个参数:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DATEDIFF(enddate,startdate)</span><br></pre></td></tr></table></figure></p>
<p>Oracle中没有等价函数</p>
<h2 id="4-3-数值函数"><a href="#4-3-数值函数" class="headerlink" title="4.3 数值函数"></a>4.3 数值函数</h2><h3 id="ROUND"><a href="#ROUND" class="headerlink" title="ROUND"></a>ROUND</h3><p>允许我们四舍五入。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ROUND(numericvalue,decimalpalaces)</span><br></pre></td></tr></table></figure></p>
<h3 id="RAND"><a href="#RAND" class="headerlink" title="RAND"></a>RAND</h3><p>用来产生随机数<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">RAND([seed])</span><br></pre></td></tr></table></figure></p>
<p>没有参数时，它会返回0-1之间的一个随机数。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT RAND() AS &apos;Random Value&apos;</span><br></pre></td></tr></table></figure></p>
<p>可选参数seed有的情况下，每次将返回相同的值。这让我想起了Python中的Random包。看来很多时候，一些东西是共通的啊。</p>
<h3 id="PI"><a href="#PI" class="headerlink" title="PI"></a>PI</h3><p><code>PI()</code>函数<br>如果想要对它保留两位小数，可以通过复合函数进行：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT ROUND(PI(),2)</span><br></pre></td></tr></table></figure></p>
<p>将会返回：3.14</p>
<h2 id="4-4-转换函数"><a href="#4-4-转换函数" class="headerlink" title="4.4 转换函数"></a>4.4 转换函数</h2><h3 id="CAST函数"><a href="#CAST函数" class="headerlink" title="CAST函数"></a>CAST函数</h3><p>允许我们把数据从一种类型转换成另一种类型。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CAST(expression AS DateType)</span><br></pre></td></tr></table></figure></p>
<p>例子：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">&apos;2009-04-11&apos; AS &apos;Original Date&apos;,</span><br><span class="line">CAST(&apos;2009--04-11&apos; AS DATETIME) AS &apos;Converted Date&apos;</span><br></pre></td></tr></table></figure></p>
<h3 id="ISNULL函数，很有用"><a href="#ISNULL函数，很有用" class="headerlink" title="ISNULL函数，很有用"></a>ISNULL函数，很有用</h3><p>可以把NULL值转换成一个有意义的值。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT Description,</span><br><span class="line">ISNULL(Color,&apos;Unknown&apos;) AS &apos;Color&apos;</span><br><span class="line">FROM Products</span><br></pre></td></tr></table></figure></p>
<h1 id="五、排序函数"><a href="#五、排序函数" class="headerlink" title="五、排序函数"></a>五、排序函数</h1><h2 id="5-1-添加排序"><a href="#5-1-添加排序" class="headerlink" title="5.1 添加排序"></a>5.1 添加排序</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT columnlist</span><br><span class="line">FROM tablelist</span><br><span class="line">ORDER BY columnlist</span><br></pre></td></tr></table></figure>
<p>默认是升序，<code>ASC</code>，因此，上面等价于：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT columnlist</span><br><span class="line">FROM tablelist</span><br><span class="line">ORDER BY columnlist ASC</span><br></pre></td></tr></table></figure></p>
<h2 id="5-2-降序"><a href="#5-2-降序" class="headerlink" title="5.2 降序"></a>5.2 降序</h2><p>使用<code>DESC</code>关键字：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT columnlist</span><br><span class="line">FROM tablelist</span><br><span class="line">ORDER BY columnlist DESC</span><br></pre></td></tr></table></figure></p>
<h2 id="5-3-根据多列"><a href="#5-3-根据多列" class="headerlink" title="5.3 根据多列"></a>5.3 根据多列</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">FirstName,</span><br><span class="line">LastName</span><br><span class="line">FROM Customers</span><br><span class="line">ORDER BY LastName, FirstName</span><br></pre></td></tr></table></figure>
<p>注意：列的顺序很重要，首先按照LastName排序，然后按照FirstName排序。</p>
<h2 id="5-4-根据计算字段"><a href="#5-4-根据计算字段" class="headerlink" title="5.4 根据计算字段"></a>5.4 根据计算字段</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT LastName+&apos;,&apos;+FirstName AS &apos;Name&apos;</span><br><span class="line">FROM Customers</span><br><span class="line">ORDER BY Name</span><br></pre></td></tr></table></figure>
<p>因此，从这儿可以知道，列别名不可以用在WHERE中，但可以用在ORDER BY中。<br>例子<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT FirstName,LastName</span><br><span class="line">FROM Customers</span><br><span class="line">ORDER BY LastName+FirstName AS &apos;Name&apos;</span><br></pre></td></tr></table></figure></p>
<h2 id="5-5-排序补充内容"><a href="#5-5-排序补充内容" class="headerlink" title="5.5 排序补充内容"></a>5.5 排序补充内容</h2><p>当数据升序时，出现顺序是如下：</p>
<blockquote>
<p>NULL-&gt;数字-&gt;字符<br>注意：此时，该列中的数字其实是按照字符来算的，因此，升序时，23也是排在5之前的。</p>
</blockquote>
<h1 id="六、基于列的逻辑-CASE"><a href="#六、基于列的逻辑-CASE" class="headerlink" title="六、基于列的逻辑-CASE"></a>六、基于列的逻辑-CASE</h1><h2 id="6-1-IF-THEN-ELSE逻辑"><a href="#6-1-IF-THEN-ELSE逻辑" class="headerlink" title="6.1 IF-THEN-ELSE逻辑"></a>6.1 IF-THEN-ELSE逻辑</h2><p>包含列和CASE表达式的SELECT语句，大概如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">column1,</span><br><span class="line">column2,</span><br><span class="line">CaseExpression</span><br><span class="line">FROM table</span><br></pre></td></tr></table></figure></p>
<h2 id="6-2-CASE-简单格式"><a href="#6-2-CASE-简单格式" class="headerlink" title="6.2 CASE-简单格式"></a>6.2 CASE-简单格式</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">CASE ColumnOrExpression</span><br><span class="line">WHEN value1 THEN result1</span><br><span class="line">WHEN value2 THEN result2</span><br><span class="line">(repeat WHEN-THEN any number of times)</span><br><span class="line">[ELSE  DefaultResult]</span><br><span class="line">END</span><br></pre></td></tr></table></figure>
<p>CASE表达式对于把不好理解的值转换成有意义的描述是很有用的。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">CASE CategoryCode</span><br><span class="line">WHEN &apos;F&apos; THEN &apos;Fruit&apos;</span><br><span class="line">WHEN &apos;V&apos; THEN &apos;Vegetable&apos;</span><br><span class="line">ELSE &apos;other&apos;</span><br><span class="line">END AS &apos;Category&apos;,</span><br><span class="line">ProductDescription As &apos;Description&apos;</span><br><span class="line">FROM Products</span><br></pre></td></tr></table></figure></p>
<h2 id="6-3-CASE-查询格式"><a href="#6-3-CASE-查询格式" class="headerlink" title="6.3 CASE-查询格式"></a>6.3 CASE-查询格式</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">CASE </span><br><span class="line">WHEN condition1 THEN result1</span><br><span class="line">WHEN condition2 THEN result2</span><br><span class="line">(repeat WHEN-THEN any number of times)</span><br><span class="line">[ELSE  DefaultResult]</span><br><span class="line">END</span><br></pre></td></tr></table></figure>
<p><strong>这种格式允许在关键字WHEN后边放置较为复杂的条件表达式。</strong></p>
<p>相关问题：</p>
<ul>
<li><a href="http://stackoverflow.com/questions/5487892/sql-server-case-when-or-then-else-end-the-or-is-not-supported" target="_blank" rel="noopener">StackOverFlow-SQL Server: CASE WHEN OR THEN ELSE END =&gt; the OR is not supported</a></li>
</ul>
<h1 id="七、基于行的逻辑"><a href="#七、基于行的逻辑" class="headerlink" title="七、基于行的逻辑"></a>七、基于行的逻辑</h1><h2 id="7-1-应用查询条件"><a href="#7-1-应用查询条件" class="headerlink" title="7.1 应用查询条件"></a>7.1 应用查询条件</h2><p>终于派到WHERE出场了，注意写法顺序，再写一遍：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Select -1&gt;选择列,-2&gt;distinct,-3&gt;top</span><br><span class="line">  1&gt;…From 表</span><br><span class="line">  2&gt;…Where 条件</span><br><span class="line">  3&gt;…Group by 列</span><br><span class="line">  4&gt;…Having 筛选条件</span><br><span class="line">  6&gt;…Order by 列</span><br></pre></td></tr></table></figure></p>
<h2 id="7-2-限制行-TOP"><a href="#7-2-限制行-TOP" class="headerlink" title="7.2 限制行-TOP"></a>7.2 限制行-TOP</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">TOP Number </span><br><span class="line">Columnlist</span><br><span class="line">FROM table</span><br></pre></td></tr></table></figure>
<h2 id="7-3-TOP和ORDER-BY结合"><a href="#7-3-TOP和ORDER-BY结合" class="headerlink" title="7.3 TOP和ORDER BY结合"></a>7.3 TOP和ORDER BY结合</h2><p>关键字TOP的另一个用途是，把它和ORDER BY子句结合起来，基于特定分类，得到带有最大值的一定数量的行。</p>
<p>假设你想看到Shakespeare所著的销量最多的书。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">TOP1</span><br><span class="line">Title AS &apos;Book Title&apos;,</span><br><span class="line">CurrentMonthSales AS &apos;Quantuty Sold&apos;</span><br><span class="line">FROM Books</span><br><span class="line">WHERE Author=&apos;Shakespeare&apos;</span><br><span class="line">ORDER BY CurrentMonthSales DESC</span><br></pre></td></tr></table></figure></p>
<p>ps: 学会利用google搜索，例如，我想要知道oracle中类似top作用的关键字是什么，可以：<br><img src="http://ww4.sinaimg.cn/large/6d9475f6jw1f2tydodr55j20jc0eq43d.jpg" alt></p>
<h1 id="八、布尔逻辑"><a href="#八、布尔逻辑" class="headerlink" title="八、布尔逻辑"></a>八、布尔逻辑</h1><p>关键字：AND/OR/NOT/BETWEEN/IN/IS/NULL</p>
<h2 id="8-1-OR"><a href="#8-1-OR" class="headerlink" title="8.1 OR"></a>8.1 OR</h2><p>OR子句意味着，如果确定任意条件为真，那么就该选中该行。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT userid,name,phone</span><br><span class="line">FROM users</span><br><span class="line">WHERE age&lt;18</span><br><span class="line">OR age&gt;60</span><br></pre></td></tr></table></figure></p>
<h2 id="8-2-使用圆括号"><a href="#8-2-使用圆括号" class="headerlink" title="8.2 使用圆括号"></a>8.2 使用圆括号</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT CustomerName,</span><br><span class="line">Sate,</span><br><span class="line">QuantityPurchased</span><br><span class="line">FROM Orders</span><br><span class="line">WHERE State =&apos;IL&apos;</span><br><span class="line">OR State=&apos;CA&apos;</span><br><span class="line">AND QuantityPurchased&gt;8</span><br></pre></td></tr></table></figure>
<p>本来想要的结果是对来自IL或者CA的客户，同时，只看数量大于8的订单。但是上面执行的结果不是这样的，因为，SQL总是会先处理AND操作符！！！然后才会处理OR操作符。所以，上述语句中，先看到AND并执行如下的条件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">State= &apos;CA&apos;</span><br><span class="line">AND QuantityPurchased&gt;8</span><br></pre></td></tr></table></figure></p>
<p>因此，要用括号来规定顺序：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT CustomerName,</span><br><span class="line">Sate,</span><br><span class="line">QuantityPurchased</span><br><span class="line">FROM Orders</span><br><span class="line">WHERE (State =&apos;IL&apos;</span><br><span class="line">OR State=&apos;CA&apos;)</span><br><span class="line">AND QuantityPurchased&gt;8</span><br></pre></td></tr></table></figure></p>
<h2 id="8-3-NOT操作符"><a href="#8-3-NOT操作符" class="headerlink" title="8.3 NOT操作符"></a>8.3 NOT操作符</h2><p>NOT操作符表示对后边的内容否定或者取反。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT CustomerName,State</span><br><span class="line">FROM Orders</span><br><span class="line">WHERE NOT (State=&apos;IL&apos; OR Sate=&apos;NY&apos;)</span><br></pre></td></tr></table></figure></p>
<p>这个其实可以用AND改写的！！！<br>NOT操作符在逻辑上不是必须的。</p>
<h2 id="8-4-BETWEEN操作符"><a href="#8-4-BETWEEN操作符" class="headerlink" title="8.4 BETWEEN操作符"></a>8.4 BETWEEN操作符</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT CustomerName,</span><br><span class="line">Sate,</span><br><span class="line">QuantityPurchased</span><br><span class="line">FROM Orders</span><br><span class="line">WHERE QuantityPurchased BETWEEN 8 AND 10</span><br></pre></td></tr></table></figure>
<h2 id="8-5-IN操作符"><a href="#8-5-IN操作符" class="headerlink" title="8.5 IN操作符"></a>8.5 IN操作符</h2><p>假设你想看到IL或者NY的行：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT *</span><br><span class="line">FROM Orders</span><br><span class="line">WHERE State=&apos;IL&apos;</span><br><span class="line">OR State=&apos;CA&apos;</span><br></pre></td></tr></table></figure></p>
<p>可以改写成：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT *</span><br><span class="line">FROM Orders</span><br><span class="line">WHERE State IN (&apos;IL&apos;,&apos;CA&apos;)</span><br></pre></td></tr></table></figure></p>
<h2 id="8-9-布尔逻辑-IS-NULL"><a href="#8-9-布尔逻辑-IS-NULL" class="headerlink" title="8.9 布尔逻辑-IS NULL"></a>8.9 布尔逻辑-IS NULL</h2><p>为了将某字段NULL值的行或0的行包括进来：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT *</span><br><span class="line">FROM Products</span><br><span class="line">WHERE weight=0</span><br><span class="line">OR weight IS NULL</span><br></pre></td></tr></table></figure></p>
<p>或者<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT *</span><br><span class="line">FROM Products</span><br><span class="line">WHERE ISNULL(weight,0)=0</span><br></pre></td></tr></table></figure></p>
<h1 id="九、模糊匹配"><a href="#九、模糊匹配" class="headerlink" title="九、模糊匹配"></a>九、模糊匹配</h1><h2 id="9-1-LIKE和-搭配"><a href="#9-1-LIKE和-搭配" class="headerlink" title="9.1 LIKE和%搭配"></a>9.1 LIKE和%搭配</h2><p>%通配符可以表示任意的字符，它可以表示0个，1个，任意多个字符。</p>
<h2 id="9-2-通配符"><a href="#9-2-通配符" class="headerlink" title="9.2 通配符"></a>9.2 通配符</h2><p>除了%以外，还有下划线（_）、方括号起来的characterlist，以及用方括号括起来的脱字符号（^）加上characterlist。</p>
<ul>
<li>下划线表示一个字符</li>
<li>[characterlist]表示括号中字符的任意一个</li>
<li>[^characterlist]表示不能是括号中字符的任意一个<br>例子：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">FirstName,</span><br><span class="line">LastName</span><br><span class="line">FROM Actors</span><br><span class="line">WHERE FirstName LIKE &apos;[CM]ARY&apos;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>检索以C或者M开头并以ARY结尾的所有行。</p>
<h3 id="9-3-按照读音匹配"><a href="#9-3-按照读音匹配" class="headerlink" title="9.3 按照读音匹配"></a>9.3 按照读音匹配</h3><p>SOUNDEX和DIFFERENCE</p>
<h1 id="十、汇总数据"><a href="#十、汇总数据" class="headerlink" title="十、汇总数据"></a>十、汇总数据</h1><h2 id="10-1消除重复"><a href="#10-1消除重复" class="headerlink" title="10.1消除重复"></a>10.1消除重复</h2><p>使用DISTINCT<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT DISTINCE name,age</span><br><span class="line">FROM users</span><br></pre></td></tr></table></figure></p>
<p>如果age不同，即使name相同，那么这一行就不会被删除重复。</p>
<h2 id="10-2-聚合函数"><a href="#10-2-聚合函数" class="headerlink" title="10.2 聚合函数"></a>10.2 聚合函数</h2><p>COUNT\SUM\AVG\MIN\MAX，他们提供了对分组数据进行计数、求和、取平均值、取最小值和最大值等方法。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">AVG(Grade) AS &apos;Average Quiz Score&apos;</span><br><span class="line">MIN(Grade) AS &apos;Minimum Quiz Score&apos;</span><br><span class="line">FROM Grades</span><br><span class="line">WHERE GradeType=&apos;Quiz&apos;</span><br></pre></td></tr></table></figure></p>
<h3 id="COUNT函数可以有3中不同方式使用它。"><a href="#COUNT函数可以有3中不同方式使用它。" class="headerlink" title="COUNT函数可以有3中不同方式使用它。"></a>COUNT函数可以有3中不同方式使用它。</h3><p>1.COUNT函数可以用来返回所有选中行的数目，而不管任何特定列的值。<br>例如：下面语句返回GradeType为’HomeWork’的所有行的数目：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">COUNT(*) AS &apos;Count of Homework Rows&apos;</span><br><span class="line">FROM Grades</span><br><span class="line">WHERE GradeType=&apos;HomeWork&apos;</span><br></pre></td></tr></table></figure></p>
<p>这种*方式，会计数所有行的个数，即使其中有<strong>NULL</strong>。</p>
<p>2.第二种方式指定具体的列<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">COUNT(Grades) AS &apos;Count of Homework Rows&apos;</span><br><span class="line">FROM Grades</span><br><span class="line">WHERE GradeType=&apos;HomeWork&apos;</span><br></pre></td></tr></table></figure></p>
<p>第一种方式返回3，这一种方式返回2，为什么？？？因为，这种方式要满足Grades这一列有值，NULL值的行不会计数。</p>
<p>3.使用关键字DISTINCT。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">COUNT(DISTINCT FeeType) AS &apos;Number of Fee Types&apos;</span><br><span class="line">FROM Fees</span><br></pre></td></tr></table></figure></p>
<p>这条语句计数了FeeType列唯一值的个数。</p>
<h2 id="10-3-分组数据-GROUP-BY"><a href="#10-3-分组数据-GROUP-BY" class="headerlink" title="10.3 分组数据-GROUP BY"></a>10.3 分组数据-GROUP BY</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">GradeType AS &apos;Grade Type&apos;,</span><br><span class="line">AVG(Grade)AS &apos;Average Grade&apos;</span><br><span class="line">FROM Grades</span><br><span class="line">GROUP BY GradeType</span><br><span class="line">ORDER BY GradeType</span><br></pre></td></tr></table></figure>
<p>感觉像EXCEL中的分类汇总功能。<br>如果想把Grade为NULL值的当做0，那么可以用：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">GradeType AS &apos;Grade Type&apos;,</span><br><span class="line">AVG(ISNULL(Grade,0))AS &apos;Average Grade&apos;</span><br><span class="line">FROM Grades</span><br><span class="line">GROUP BY GradeType</span><br><span class="line">ORDER BY GradeType</span><br></pre></td></tr></table></figure></p>
<ul>
<li>GROUP BY子句中的列的顺序是没有意义的；</li>
<li>ORDER BY子句中的列的顺序是有意义的。</li>
</ul>
<h2 id="10-4-基于聚合查询条件-HAVING"><a href="#10-4-基于聚合查询条件-HAVING" class="headerlink" title="10.4 基于聚合查询条件-HAVING"></a>10.4 基于聚合查询条件-HAVING</h2><p>当针对带GROUP BY的一条SELECT语句应用任何查询条件时，人们必须要问查询条件是应用于单独的行还是整个组。</p>
<p>实际上，WHERE子句是单独的执行查询条件。SQL提供了一个名为HAVING的关键字，它允许对组级别使用查询条件。<br>例子：<br>查看选修了类型为选修“A”，平均成绩在70分以上的学生姓名，平均成绩。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">Name,</span><br><span class="line">AVG(ISNULL(Grades,0)) AS &apos;Average Grades&apos;</span><br><span class="line">FROM Grades</span><br><span class="line">WHERE GradeType=&apos;A&apos;</span><br><span class="line">GROUP BY Name</span><br><span class="line">HAVING AVG(ISNULL(Grades,0))&gt;70</span><br><span class="line">ORDER BY Name</span><br></pre></td></tr></table></figure></p>
<p>修要修类型为A，那么，这是这对行的查询，因此这里要用WHERE。<br>但是，还要筛选平均成绩，那么，这是一个平均值，建立在聚合函数上的，并不是单独的行，这就需要用到关键字HAVING。需要先将Student分组，然后把查询结果应用到基于全组的一个聚合统计上。</p>
<p>WHERE只保证我们选择了GradeType是A的行，HAVING保证平均成绩至少70分以上。</p>
<p>注意：如果想要在结果中添加GradeType的值，如果直接在SELECT后边添加这个列，将会出错。这是因为，所有列都必须要么出现在GROUP BY中，要么包含在一个聚合函数中。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">SELECT </span><br><span class="line">Name,</span><br><span class="line">GradeType,</span><br><span class="line">AVG(ISNULL(Grades,0)) AS &apos;Average Grades&apos;</span><br><span class="line">FROM Grades</span><br><span class="line">WHERE GradeType=&apos;A&apos;</span><br><span class="line">GROUP BY Name,GradeType</span><br><span class="line">HAVING AVG(ISNULL(Grades,0))&gt;70</span><br><span class="line">ORDER BY Name</span><br></pre></td></tr></table></figure></p>
<h1 id="十一、组合表"><a href="#十一、组合表" class="headerlink" title="十一、组合表"></a>十一、组合表</h1><h2 id="11-1-内连接来组合表-Inner-Join"><a href="#11-1-内连接来组合表-Inner-Join" class="headerlink" title="11.1 内连接来组合表-Inner Join"></a>11.1 内连接来组合表-Inner Join</h2><p>通过书中的描述，我感觉内连接更像是用来将主键表、外键表连接起来的工具。<br>例如：<br>A表：</p>
<table>
<thead>
<tr>
<th>userid</th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>michael</td>
<td>26</td>
</tr>
<tr>
<td>2</td>
<td>hhh</td>
<td>25</td>
</tr>
<tr>
<td>3</td>
<td>xiang</td>
<td>20</td>
</tr>
</tbody>
</table>
<p>B表：</p>
<table>
<thead>
<tr>
<th>orderid</th>
<th>userid</th>
<th>num</th>
<th>price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>6</td>
<td>6</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>5</td>
<td>5</td>
</tr>
</tbody>
</table>
<p>如上表格，那么要连接这两个表格，查询订单1的客户姓名，年龄，订单号：<br>方式一：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT name,age,orderid</span><br><span class="line">FROM A,B</span><br><span class="line">WHERE A.userid=B.userid</span><br><span class="line">AND orderid=1</span><br></pre></td></tr></table></figure></p>
<p>方式二，使用现在的内连接实现：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT name,age,orderid</span><br><span class="line">FROM A</span><br><span class="line">INNER JOIN B</span><br><span class="line">ON A.userid=B.userid</span><br><span class="line">AND orderid=1</span><br></pre></td></tr></table></figure></p>
<p>ON关键字指定两个表如何准确的连接。</p>
<p>内连接中表的顺序：FROM 子句指定了A表，INNER JOIN 子句指定B表，我们调换A,B顺序，所得到的结果相同的!只是显示列的顺序可能会不同而已。</p>
<p>不建议使用方式一的格式。关键字INNER JOIN ON的优点在于显示地表示了连接的逻辑，那是它们唯一的用途。WEHERE的含义不够明显。因为它是条件的意思啊，不是连接的！</p>
<h2 id="11-2-外连接"><a href="#11-2-外连接" class="headerlink" title="11.2 外连接"></a>11.2 外连接</h2><p>外连接分为左连接（LEFT OUTER JOIN)、右连接(RIGHT OUTER JOIN)、全连接（FULL OUTER JOIN)。</p>
<p>OUTER是可以省略的。</p>
<h3 id="左连接（LEFT-JOIN"><a href="#左连接（LEFT-JOIN" class="headerlink" title="左连接（LEFT  JOIN)"></a>左连接（LEFT  JOIN)</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT name,age,orderid</span><br><span class="line">FROM A</span><br><span class="line">LEFT JOIN B</span><br><span class="line">ON A.userid=B.userid</span><br><span class="line">AND orderid=1</span><br></pre></td></tr></table></figure>
<p>外连接的强大之处在于，主表中的数据必然都会保留，从表中列没有值的情况，用NULL补充。</p>
<p>LEFT JOIN 左边的表为主表，右边的表为从表。</p>
<h2 id="11-3-自连接"><a href="#11-3-自连接" class="headerlink" title="11.3 自连接"></a>11.3 自连接</h2><p><strong>自连接必然用到表的别名。</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT A.name,B.name as ManagerName</span><br><span class="line">FROM worker as A</span><br><span class="line">LEFT JOIN worker as B</span><br><span class="line">ON A.managerid=B.id</span><br></pre></td></tr></table></figure></p>
<h2 id="11-4-创建视图"><a href="#11-4-创建视图" class="headerlink" title="11.4 创建视图"></a>11.4 创建视图</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">CREATE VIEW ViewName AS</span><br><span class="line">SelectStatement</span><br><span class="line">[WITH CHECK OPTION]</span><br></pre></td></tr></table></figure>
<p>视图中不能包含ORDER BY子句。</p>
<p>[WITH CHECK OPTION]表示对视图进行UPDATE,INSERT,DELETE操作时任然保证了视图定义时的条件表达式。</p>
<p>删除视图：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DROP VIEW ViewName</span><br></pre></td></tr></table></figure></p>
<p>修改视图：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ALTER VIEW ViewName AS</span><br><span class="line">SelectStatement</span><br></pre></td></tr></table></figure></p>
<h3 id="视图的优点"><a href="#视图的优点" class="headerlink" title="视图的优点"></a>视图的优点</h3><ol>
<li>简化用户的操作</li>
<li>使用户以多角度看待同一数据</li>
<li>对重构数据库提供了一定程度的逻辑独立性</li>
<li>对机密数据提供安全保护</li>
</ol>
<h1 id="十二、补充"><a href="#十二、补充" class="headerlink" title="十二、补充"></a>十二、补充</h1><h2 id="12-1-子查询"><a href="#12-1-子查询" class="headerlink" title="12.1 子查询"></a>12.1 子查询</h2><p>可以用3种主要的方式来指定子查询，总结如下：</p>
<ul>
<li>当子查询是tablelist的一部分时，它指定了一个数据源。</li>
<li>当子查询是condition的一部分时，它成为查询条件的一部分。</li>
<li>当子查询是columnlist的一部分时，它创建了一个单个的计算的列。</li>
</ul>
<h2 id="12-2-索引"><a href="#12-2-索引" class="headerlink" title="12.2 索引"></a>12.2 索引</h2><p>索引是一种物理结构，可以为数据库表中任意的列添加索引。</p>
<p>索引的目的是，当SQL语句中包含该列的是偶，可以加速数据的检索。</p>
<p>索引的缺点是，在数据库中，索引需要更多的存储硬盘。另一个负面因素是，索引通常会降低相关的列数据更新速度。这是因为，任何时候插入或者修改一行记录时，索引都必须重新计算该列中的值的正确的排列顺序。</p>
<p>可以对任意的列进行索引，但是只能指定一个列作为主键。指定一个列作为主键意味着两件事情：首先这个列成为了索引，其次保证这列包含唯一的值。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">CREATE INDEX Index2</span><br><span class="line">ON MyTable (ColumnFour)</span><br></pre></td></tr></table></figure></p>
<p>删除一个索引：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">DROP INDX Index2</span><br><span class="line">ON MyTable</span><br></pre></td></tr></table></figure></p>
<h1 id="参考："><a href="#参考：" class="headerlink" title="参考："></a>参考：</h1><ul>
<li><a href="http://www.imooc.com/article/1412" target="_blank" rel="noopener">SQL总结（一）基本查询</a></li>
<li><a href="http://www.imooc.com/article/1415" target="_blank" rel="noopener">SQL Server 常用高级语法笔记</a></li>
<li><a href="http://www.codeceo.com/article/mssql-log-01.html" target="_blank" rel="noopener">史上最全的SQL Server复习笔记一</a></li>
</ul>
<script src="//w.segmentfault.com/card/1030000002497141.js?w=0&3rd=1&bg=0&bd=DDDDDD&cl=333333&btn=009a62&noBtn=0"></script>

<hr>

      
    </div>

    
      


    

    
    
    

    
      <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center;">
  <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="Michael翔 wechat" style="width: 200px; max-width: 100%;">
  <div>欢迎订阅 ヾﾉ≧∀≦)o</div>
</div>

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>我知道是不会有人点的，但万一有人想不开呢👇</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Michael翔 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.png" alt="Michael翔 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Michael翔</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="https://michael728.github.io/2016/05/03/SQL/" title="SQL基础语法笔记教程整理">https://michael728.github.io/2016/05/03/SQL/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/数据库/" rel="tag"># 数据库</a>
          
            <a href="/tags/SQL/" rel="tag"># SQL</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/12/28/tools-sougoupinyin/" rel="next" title="搜狗输入法使用技巧整理">
                <i class="fa fa-chevron-left"></i> 搜狗输入法使用技巧整理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/05/14/python-matplotlib-basic/" rel="prev" title="Python--matplotlib绘图可视化知识点整理">
                Python--matplotlib绘图可视化知识点整理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yODgyMC81Mzkw" "></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/logo.jpg" alt="Michael翔">
            
              <p class="site-author-name" itemprop="name">Michael翔</p>
              <div class="site-description motion-element" itemprop="description">DevOps CICD Blog 持续学习</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">82</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">19</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">95</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/Michael728" title="GitHub &rarr; https://github.com/Michael728" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/1838446070/profile?topnav=1&wvr=6" title="微博 &rarr; https://weibo.com/1838446070/profile?topnav=1&wvr=6" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.cnblogs.com/michael-xiang/" title="博客园 &rarr; https://www.cnblogs.com/michael-xiang/" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>博客园</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.zhihu.com/people/michaelXoX" title="知乎 &rarr; https://www.zhihu.com/people/michaelXoX" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/728_michael" title="Twitter &rarr; https://twitter.com/728_michael" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://t.me/michaelxiang" title="Telegram &rarr; https://t.me/michaelxiang" rel="noopener" target="_blank"><i class="fa fa-fw fa-telegram"></i>Telegram</a>
                </span>
              
            </div>
          

          
             <div class="cc-license motion-element" itemprop="license">
              
              
                
              
              
              
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
             </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                关注列表
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2018/09/16/blog-interesting/" title="https://michael728.github.io/2018/09/16/blog-interesting/">Blog List</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://zcheng.ren/posts/" title="https://zcheng.ren/posts/" rel="noopener" target="_blank">ZeeCoder</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ehlxr.me/" title="https://ehlxr.me/" rel="noopener" target="_blank">ehlxr</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.kawabangga.com/" title="https://www.kawabangga.com/" rel="noopener" target="_blank">卡瓦邦噶-蚂蚁SRE</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.stdioa.com/" title="https://blog.stdioa.com/" rel="noopener" target="_blank">David Dai</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://bestzuo.cn/" title="https://bestzuo.cn/" rel="noopener" target="_blank">Sanarous</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhyong.cn/" title="https://www.zhyong.cn/" rel="noopener" target="_blank">ZhangYong-爱折腾软件</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.dalaoyang.cn/" title="https://www.dalaoyang.cn/" rel="noopener" target="_blank">Dalaoyang-SpringBoot</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.wuliaole.com/index.html" title="http://www.wuliaole.com/index.html" rel="noopener" target="_blank">无聊小博</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ilovey.live/" title="http://ilovey.live/" rel="noopener" target="_blank">低调小熊猫-Java开发</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://michael728.github.io/2016/09/03/blog-logfile/" title="https://michael728.github.io/2016/09/03/blog-logfile/">建站日志</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一、关系型数据库和SQL"><span class="nav-number">1.</span> <span class="nav-text">一、关系型数据库和SQL</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-SQL语言主要有3个主要的组成部分。"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 SQL语言主要有3个主要的组成部分。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-主键和外键"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 主键和外键</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-数据类型"><span class="nav-number">1.3.</span> <span class="nav-text">1.3 数据类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-空值"><span class="nav-number">1.4.</span> <span class="nav-text">1.3 空值</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、简单增删改查"><span class="nav-number">2.</span> <span class="nav-text">二、简单增删改查</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-查（列名有空格的情况）"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 查（列名有空格的情况）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#查询顺序-SQL执行顺序-2："><span class="nav-number">2.1.1.</span> <span class="nav-text">查询顺序,SQL执行顺序^2：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-增"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 增</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-改"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 改</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-删"><span class="nav-number">2.4.</span> <span class="nav-text">2.4 删</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三、别名"><span class="nav-number">3.</span> <span class="nav-text">三、别名</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-计算字段"><span class="nav-number">3.1.</span> <span class="nav-text">3.1 计算字段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-直接量"><span class="nav-number">3.2.</span> <span class="nav-text">3.2 直接量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-算数运算"><span class="nav-number">3.3.</span> <span class="nav-text">3.3 算数运算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-4-别名"><span class="nav-number">3.4.</span> <span class="nav-text">3.4 别名</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#四、使用函数"><span class="nav-number">4.</span> <span class="nav-text">四、使用函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-字符函数"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 字符函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#LEFT-amp-RIGHT"><span class="nav-number">4.1.1.</span> <span class="nav-text">LEFT&amp;RIGHT</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#LTRIM-amp-RTRIM"><span class="nav-number">4.1.2.</span> <span class="nav-text">LTRIM&amp;RTRIM</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SUBSTRING"><span class="nav-number">4.1.3.</span> <span class="nav-text">SUBSTRING</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-日期-时间函数"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 日期/时间函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#GETDATE"><span class="nav-number">4.2.1.</span> <span class="nav-text">GETDATE</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DATEPART"><span class="nav-number">4.2.2.</span> <span class="nav-text">DATEPART</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DATEDIFF"><span class="nav-number">4.2.3.</span> <span class="nav-text">DATEDIFF</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-数值函数"><span class="nav-number">4.3.</span> <span class="nav-text">4.3 数值函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ROUND"><span class="nav-number">4.3.1.</span> <span class="nav-text">ROUND</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RAND"><span class="nav-number">4.3.2.</span> <span class="nav-text">RAND</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PI"><span class="nav-number">4.3.3.</span> <span class="nav-text">PI</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-4-转换函数"><span class="nav-number">4.4.</span> <span class="nav-text">4.4 转换函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#CAST函数"><span class="nav-number">4.4.1.</span> <span class="nav-text">CAST函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ISNULL函数，很有用"><span class="nav-number">4.4.2.</span> <span class="nav-text">ISNULL函数，很有用</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#五、排序函数"><span class="nav-number">5.</span> <span class="nav-text">五、排序函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-添加排序"><span class="nav-number">5.1.</span> <span class="nav-text">5.1 添加排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-降序"><span class="nav-number">5.2.</span> <span class="nav-text">5.2 降序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-根据多列"><span class="nav-number">5.3.</span> <span class="nav-text">5.3 根据多列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-4-根据计算字段"><span class="nav-number">5.4.</span> <span class="nav-text">5.4 根据计算字段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-5-排序补充内容"><span class="nav-number">5.5.</span> <span class="nav-text">5.5 排序补充内容</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#六、基于列的逻辑-CASE"><span class="nav-number">6.</span> <span class="nav-text">六、基于列的逻辑-CASE</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#6-1-IF-THEN-ELSE逻辑"><span class="nav-number">6.1.</span> <span class="nav-text">6.1 IF-THEN-ELSE逻辑</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-2-CASE-简单格式"><span class="nav-number">6.2.</span> <span class="nav-text">6.2 CASE-简单格式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-3-CASE-查询格式"><span class="nav-number">6.3.</span> <span class="nav-text">6.3 CASE-查询格式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#七、基于行的逻辑"><span class="nav-number">7.</span> <span class="nav-text">七、基于行的逻辑</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#7-1-应用查询条件"><span class="nav-number">7.1.</span> <span class="nav-text">7.1 应用查询条件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-2-限制行-TOP"><span class="nav-number">7.2.</span> <span class="nav-text">7.2 限制行-TOP</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-3-TOP和ORDER-BY结合"><span class="nav-number">7.3.</span> <span class="nav-text">7.3 TOP和ORDER BY结合</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#八、布尔逻辑"><span class="nav-number">8.</span> <span class="nav-text">八、布尔逻辑</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#8-1-OR"><span class="nav-number">8.1.</span> <span class="nav-text">8.1 OR</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-2-使用圆括号"><span class="nav-number">8.2.</span> <span class="nav-text">8.2 使用圆括号</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-3-NOT操作符"><span class="nav-number">8.3.</span> <span class="nav-text">8.3 NOT操作符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-4-BETWEEN操作符"><span class="nav-number">8.4.</span> <span class="nav-text">8.4 BETWEEN操作符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-5-IN操作符"><span class="nav-number">8.5.</span> <span class="nav-text">8.5 IN操作符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-9-布尔逻辑-IS-NULL"><span class="nav-number">8.6.</span> <span class="nav-text">8.9 布尔逻辑-IS NULL</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#九、模糊匹配"><span class="nav-number">9.</span> <span class="nav-text">九、模糊匹配</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#9-1-LIKE和-搭配"><span class="nav-number">9.1.</span> <span class="nav-text">9.1 LIKE和%搭配</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-2-通配符"><span class="nav-number">9.2.</span> <span class="nav-text">9.2 通配符</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#9-3-按照读音匹配"><span class="nav-number">9.2.1.</span> <span class="nav-text">9.3 按照读音匹配</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#十、汇总数据"><span class="nav-number">10.</span> <span class="nav-text">十、汇总数据</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#10-1消除重复"><span class="nav-number">10.1.</span> <span class="nav-text">10.1消除重复</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-2-聚合函数"><span class="nav-number">10.2.</span> <span class="nav-text">10.2 聚合函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#COUNT函数可以有3中不同方式使用它。"><span class="nav-number">10.2.1.</span> <span class="nav-text">COUNT函数可以有3中不同方式使用它。</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-3-分组数据-GROUP-BY"><span class="nav-number">10.3.</span> <span class="nav-text">10.3 分组数据-GROUP BY</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-4-基于聚合查询条件-HAVING"><span class="nav-number">10.4.</span> <span class="nav-text">10.4 基于聚合查询条件-HAVING</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#十一、组合表"><span class="nav-number">11.</span> <span class="nav-text">十一、组合表</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#11-1-内连接来组合表-Inner-Join"><span class="nav-number">11.1.</span> <span class="nav-text">11.1 内连接来组合表-Inner Join</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-2-外连接"><span class="nav-number">11.2.</span> <span class="nav-text">11.2 外连接</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#左连接（LEFT-JOIN"><span class="nav-number">11.2.1.</span> <span class="nav-text">左连接（LEFT  JOIN)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-3-自连接"><span class="nav-number">11.3.</span> <span class="nav-text">11.3 自连接</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-4-创建视图"><span class="nav-number">11.4.</span> <span class="nav-text">11.4 创建视图</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#视图的优点"><span class="nav-number">11.4.1.</span> <span class="nav-text">视图的优点</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#十二、补充"><span class="nav-number">12.</span> <span class="nav-text">十二、补充</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#12-1-子查询"><span class="nav-number">12.1.</span> <span class="nav-text">12.1 子查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-2-索引"><span class="nav-number">12.2.</span> <span class="nav-text">12.2 索引</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考："><span class="nav-number">13.</span> <span class="nav-text">参考：</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Michael翔</span>

  

  
</div>









        








        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
      
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1.0.0/canvas-nest.min.js"></script>













  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.js"></script>


  


  <script src="/js/utils.js?v=7.1.1"></script>

  <script src="/js/motion.js?v=7.1.1"></script>



  
  


  <script src="/js/affix.js?v=7.1.1"></script>

  <script src="/js/schemes/pisces.js?v=7.1.1"></script>




  
  <script src="/js/scrollspy.js?v=7.1.1"></script>
<script src="/js/post-details.js?v=7.1.1"></script>



  


  <script src="/js/next-boot.js?v=7.1.1"></script>


  

  

  

  


  
    <script>
  window.livereOptions = {
    refer: '2016/05/03/SQL/'
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>

  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
